package model

import (
	"api/database"
	"api/utils/logger"
	"github.com/jinzhu/gorm"
	"time"
)

/**
 * @Description
 * @Author huan.wang
 * @Date 2021/5/5 8:24 下午
 **/

type UserModel struct {
	gorm.Model
	BaseModel
	Phone    string `gorm:"unique_index;not null;size:11"`
	Name     string `gorm:"column:name"`
	Password string `gorm:"column:password"`
	LastLoginIp string `gorm:"column:lastLoginIp"`
	LastLoginTime time.Time
	Devices []DeviceModel `gorm:"foreignKey:UID"`
}

func NewUserModel() *UserModel {
	return &UserModel{}
}

func (UserModel)  TableName() string {
	return "user"
}

func (um UserModel) Insert() (interface{}, error) {
	if err := database.GetDB().Create(&um).Error; err != nil {
		logger.Error.Println("[Model] insert error", err)
		return nil, err
	}
	var id []uint
	database.GetDB().Raw("select LAST_INSERT_ID() as id").Pluck("id", &id)
	return id[0], nil
}

func (um UserModel) Delete() (interface{}, error) {
	return nil, nil
}

func (um UserModel) Update() (interface{}, error) {
	database.GetDB().Save(&um)
	return nil,nil
}

func (um UserModel) Select() (user UserModel) {
	database.GetDB().Find(&user)
	return
}
func (um UserModel) SelectByPhone() (user UserModel) {
	database.GetDB().Where("phone = ?",um.Phone).Find(&user)
	return
}
